<?php
	
	
class M_grade_level_sections Extends CI_Model
{
	private $__table ='grade_level_sections';
	
	function get_all_records(){
		$sql = "SELECT * FROM grade_level_sections"; 
		$q = $this->db->query($sql); 
		return $q->num_rows() >= 1 ? $q->result() : FALSE;
	}
	
	function get_all_sections(){
		$sql = "SELECT sections.*, grade_level_sections.section_id, grade_level_sections.level_id  FROM sections LEFT JOIN grade_level_sections ON sections.id = grade_level_sections.section_id ORDER BY sections.section_name";
		$q = $this->db->query($sql); 
		return $q->num_rows() >= 1 ? $q->result() : FALSE;
	}
	
	public function count_enrollees_per_section($sy_from=FALSE,$sy_to=FALSE)
	{
		$sql = "SELECT e_section_id, e_grade_level  FROM enrollments WHERE e_sy_from = $sy_from AND e_sy_to = $sy_to";
		$q = $this->db->query($sql); 
		return $q->num_rows() >= 1 ? $q->result() : FALSE;
		//return $this->db->where('e_sy_from',$sy_from)->where('e_sy_to',$sy_to)->count_all($this->__table);
	}
	
	function get_assigned_sections($level_id){
		$sql = "SELECT sections.*  FROM sections LEFT JOIN grade_level_sections ON sections.id = grade_level_sections.section_id WHERE grade_level_sections.level_id = $level_id";
		$q = $this->db->query($sql); 
		return $q->num_rows() >= 1 ? $q->result() : FALSE;
	}
	
	function get_enrollees($section_id,$level_id)
	{
		$sql = 'SELECT profiles.idno, profiles.firstname, profiles.lastname, profiles.middlename FROM profiles LEFT JOIN enrollments ON profiles.profile_id = enrollments.e_profile_id WHERE enrollments.e_section_id = '.$section_id.' AND enrollments.e_grade_level = '.$level_id.' ORDER BY profiles.lastname';
		$get_profile_query = $this->db->query($sql);
		return $get_profile_query->num_rows() >= 1 ? $get_profile_query->result() : FALSE;
	}
	
	function get_other_sections($level_id)
	{
		$sql ="SELECT * FROM sections 
			   WHERE sections.id NOT IN (SELECT section_id FROM grade_level_sections WHERE level_id = ?)
			   AND level_assigned = ?"; 
		$q = $this->db->query($sql,array($level_id,'no')); 
		return $q->num_rows() >= 1 ? $q->result() : FALSE;
	}
	
	function assign_sections($subjects){
		$this->db->insert_batch('grade_level_sections',$subjects);
		return $this->db->affected_rows() >= 1 ? TRUE : FALSE;
	}
	
	function unassign_subjects($ss_id, $section_id){
		$this->db->where('level_id', $section_id)->where_in('section_id', $ss_id)->delete('grade_level_sections');
		return $this->db->affected_rows() >= 1 ? TRUE : FALSE;
	}

	function get_section_by_level($id)
	{
		$sql = "select level_id,section_id,gls.id,section_name from grade_level_sections as gls
				Join sections on sections.id = gls.section_id
				where gls.level_id = ? 
				AND sections.room_assigned =?";
		
		$query = $this->db->query($sql,array($id,'no'));
		return $query->num_rows() > 0 ? $query->result() : FALSE;
	}
	
}
